package service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dao.OrderDao;
import entity.Cart;
import entity.CartItem;
import entity.Item;
import entity.Order;
import entity.ReceiveAddress;
import entity.User;

public class OrderService {
	/**
	 * 根据用户id查询出该用户所有的收货地址
	 * @param user_id
	 * @return
	 * @throws Exception 
	 */
	public List<ReceiveAddress> getAddress(Integer user_id) throws Exception{
		return new OrderDao().getAddress(user_id);
	}
	
	public ReceiveAddress getAddressById(User user, Integer id) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("user_id", user.getId());
		paramMap.put("id", id);
		return new OrderDao().getAddressById(paramMap);
	}
	
	public void saveOrder(User user, ReceiveAddress ra, Order order, Cart cart) throws Exception {
		OrderDao dao = new OrderDao();
		
		//保存收货地址
		ra.setUser_id(user.getId());
		dao.saveReceiveAddress(ra);
		
		//保存订单
		order.setUser_id(user.getId());
		order.setStatus(1);
		order.setOrder_time(new java.util.Date().getTime());
		order.setOrder_desc("");
		order.setTotal_price(cart.getTotalPrice());
		Integer orderId = dao.saveOrder(order);
		
		//保存订单的具体每一项
		List<CartItem> items = cart.list();
		CartItem cItem = null;
		for(int i = 0; i < items.size(); i++){
			cItem = items.get(i);
			Item oItem = new Item();
			oItem.setOrder_id(orderId);
			oItem.setProduct_id(cItem.getProduct().getId());
			oItem.setProduct_name(cItem.getProduct().getProduct_name());
			oItem.setDang_price(cItem.getProduct().getDang_price());
			oItem.setProduct_num(cItem.getCount());
			oItem.setAmount(cItem.getProduct().getDang_price() * cItem.getCount());
			dao.saveItem(oItem);
		}
	}
}
